<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      
    >
      <el-form-item label="WDR号码" prop="wdr">
        <el-input
          v-model="queryParams.wdr"
          placeholder="请输入WDR号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="生产车间" prop="productWorkshop">
        <el-select
          v-model="queryParams.productWorkshop"
          placeholder="请选择生产车间"
          clearable
        >
          <el-option
            v-for="dict in dict.type.product_order_workshop"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="车间订单号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入车间订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="订单录入时间">
        <el-date-picker
          v-model="daterangeStartTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:order:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:order:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:order:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-download"
          size="mini"
          @click="handleImport"
          >导入</el-button
        > </el-col
      ><!-- 用户导入对话框 -->
      <el-dialog
        :title="upload.title"
        :visible.sync="upload.open"
        width="400px"
      >
        <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?updateSupport=' + upload.updateSupport"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            将文件拖到此处，或
            <em>点击上传</em>
          </div>
          <div class="el-upload__tip" slot="tip">
            <el-checkbox
              v-model="upload.updateSupport"
            />是否更新已经存在的用户数据
            <el-link type="info" style="font-size: 12px" @click="importTemplate"
              >下载模板</el-link
            >
          </div>
          <div class="el-upload__tip" style="color: red" slot="tip">
            提示：仅允许导入“xls”或“xlsx”格式文件！
          </div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </el-dialog>
      <!-- <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose"
      >
        <form enctype="multipart/form-data" class="mt40 mb20">
          <div class="col-xs-offset-1">
            <input type="file" id="file" name="file" />
            <div class="mt10 pt5">
              <input
                type="checkbox"
                id="updateSupport"
                name="updateSupport"
                title="如果登录账户已经存在，更新这条数据。"
              />
              是否更新已经存在的数据 &nbsp;
              <a
                onclick="$.table.importTemplate()"
                class="btn btn-default btn-xs"
                ><i class="fa fa-file-excel-o"></i> 下载模板</a
              >
            </div>
            <font color="red" class="pull-left mt10">
              提示：仅允许导入“xls”或“xlsx”格式文件！
            </font>
          </div>
        </form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogVisible = false"
            >确 定</el-button
          >
        </span>
      </el-dialog> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:order:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="orderList"
      border
      @selection-change="handleSelectionChange"
      :header-cell-style="{
        background: 'rgb(64, 158, 255)',
        color: '#fff',
      }"
    >
      <el-table-column type="selection" width="40" align="center" />
      <el-table-column label="序号" align="center" prop="orderId" width="50" />
      <el-table-column label="WDR号码" align="center" prop="wdr" width="126" />

      <el-table-column
        label="车间订单号"
        align="center"
        prop="orderNo"
        width="120"
      />
      <el-table-column
        label="货物描述"
        align="center"
        prop="orderDescribe"
        width="200"
      />
      <el-table-column label="订单数量" align="center" prop="orderNum" />
      <el-table-column label="订单状态" align="center" prop="orderState">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.order_state"
            :value="scope.row.orderState"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="订单开始生产时间"
        align="center"
        prop="productTime"
        width="160"
      />
      <el-table-column
        label="订单完结时间"
        align="center"
        prop="endTime"
        width="160"
      />
      <el-table-column label="合格率" align="center" prop="yield" />
      <el-table-column label="蜡重(g)" align="center" prop="weight" />
      <el-table-column label="进度" align="center" prop="progress" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="100px"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:order:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:order:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
      <el-table-column
        label="详情"
        align="center"
        class-name="small-padding fixed-width"
        width="100px"
      >
        <template slot-scope="scope">
          <el-button type="primary" @click="routeOrderDetail(scope.row.id)"
            >查看详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="WDR号码" prop="wdr">
          <el-input v-model="form.wdr" placeholder="请输入WDR号码" />
        </el-form-item>
        <el-form-item label="生产车间" prop="productWorkshop">
          <el-select
            v-model="form.productWorkshop"
            placeholder="请选择生产车间"
          >
            <el-option
              v-for="dict in dict.type.product_order_workshop"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="车间订单号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入车间订单号" />
        </el-form-item>
        <el-form-item label="零件号" prop="partNo">
          <el-input v-model="form.partNo" placeholder="请输入零件号" />
        </el-form-item>
        <el-form-item label="货物描述" prop="orderDescribe">
          <el-input v-model="form.orderDescribe" placeholder="请输入货物描述" />
        </el-form-item>
        <el-form-item label="订单数量" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="请输入订单数量" />
        </el-form-item>
        <el-form-item label="颜色" prop="orderNum">
          <el-input v-model="form.color" placeholder="请输入订单颜色" />
        </el-form-item>
        <el-form-item label="蜡重" prop="orderNum">
          <el-input v-model="form.weight" placeholder="请输入蜡重" />
        </el-form-item>
        <el-form-item label="时间" prop="startTime">
          <el-date-picker
            v-model="form.startTime"
            type="datetime"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { importTemplate } from "@/api/system/user";

import {
  listOrder,
  getOrder,
  delOrder,
  addOrder,
  updateOrder,
  orderP
} from "@/api/system/order";
export default {
  name: "Order",
  dicts: ["order_state", "product_order_workshop"],
  data() {
    return {
      newList: [],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/order/importData",
      },
      dialogVisible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],

      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单管理表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 进度时间范围
      daterangeStartTime: [],
      // 进度时间范围
      daterangeEndTime: [],
      // 进度时间范围
      daterangeProductTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 25,
        orderId: null,
        wdr: null,
        productWorkshop: null,
        orderNo: null,
        partNo: null,
        orderDescribe: null,
        orderNum: null,
        orderState: null,
        startTime: null,
        endTime: null,
        productTime: null,
        yield: null,
        progress: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    this.orderNofn();
  },
  methods: {
    onClick() {
      alert("yyds");
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    /** 查询订单管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeStartTime && "" != this.daterangeStartTime) {
        this.queryParams.params["beginStartTime"] = this.daterangeStartTime[0];
        this.queryParams.params["endStartTime"] = this.daterangeStartTime[1];
      }
      if (null != this.daterangeEndTime && "" != this.daterangeEndTime) {
        this.queryParams.params["beginEndTime"] = this.daterangeEndTime[0];
        this.queryParams.params["endEndTime"] = this.daterangeEndTime[1];
      }
      if (
        null != this.daterangeProductTime &&
        "" != this.daterangeProductTime
      ) {
        this.queryParams.params["beginProductTime"] =
          this.daterangeProductTime[0];
        this.queryParams.params["endProductTime"] =
          this.daterangeProductTime[1];
      }
      listOrder(this.queryParams).then((response) => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
        console.log(this.orderList);
        this.orderList.map((item, index, arr) => {
          if (item.wdr !== null) {
            if (item.wdr.indexOf("*") !== -1) {
              item.wdr = item.wdr.replace(/\*/g, "\n");
            }
          }
          if (item.orderNo !== null) {
            if (item.orderNo.indexOf("*") !== -1) {
              item.orderNo = item.orderNo.replace(/\*/g, "\n");
            }
            if (item.orderNo.indexOf(".") !== -1) {
              item.orderNo = item.orderNo.replace(/\./g, "\n");
            }
          }
        });
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderId: null,
        wdr: null,
        productWorkshop: null,
        orderNo: null,
        partNo: null,
        orderDescribe: null,
        orderNum: null,
        orderState: null,
        startTime: null,
        endTime: null,
        productTime: null,
        yield: null,
        progress: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeStartTime = [];
      this.daterangeEndTime = [];
      this.daterangeProductTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getOrder(id).then((response) => {
        console.log(response.data);
        this.form = response.data;
        this.open = true;
        this.title = "修改订单管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateOrder(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              console.log(this.form, "90086");

              this.open = false;
              this.getList();
            });
          } else {
            addOrder(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除订单管理编号为"' + ids + '"的数据项？')
        .then(function () {
          return delOrder(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/order/export",
        {
          ...this.queryParams,
        },
        `order_${new Date().getTime()}.xlsx`
      );
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    // 下载模版
    importTemplate() {
      this.download(
        "system/order/importTemplate",
        {},
        `user_template_${new Date().getTime()}.xlsx`
      );
    },
    /** 下载模板操作 */

    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    routeOrderDetail(id) {
      this.$store.dispatch("orderDetail/orderListAPI", id);
      this.$store.dispatch("orderDetail/orderFlowMesListAPI", id);
      this.$store.dispatch("orderDetail/orderStopMesAPI", id);
      this.$router.push({
        path: "/orderDetail",
      });
    },
    orderNofn() {
      // console.log(this.orderList[0].orderNo.replace(/\*/g, "\n"));
      // this.orderList[0].orderNo.replace(/\*/g, "\n");
      // this.orderList[0].map((item, index, array) => {
      //   return item.replace(/\*/g, "\n");
      // });
      console.log(this.newList, "new");
      this.newList.forEach((item) => {
        console.log(item);
      });
    },
  },
};
</script>
<style scoped>
.app-container >>> .el-table .cell {
  white-space: pre-wrap;
}
</style>
